<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="正则表达式,Linux命令," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;awk 是一种处理文本文件的语言，是一个强大的文本分析工具。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;之所以叫AWK是因为其取了三位创始人 Alfred Aho，Peter Weinberger, 和 Brian Kernighan 的Family">
<meta name="keywords" content="正则表达式,Linux命令">
<meta property="og:type" content="article">
<meta property="og:title" content="Linux 命令- awk">
<meta property="og:url" content="https://hcldirgit.github.io/2017/09/03/2. Linux 命令/71. Linux 命令- awk/index.html">
<meta property="og:site_name" content="失落的乐章">
<meta property="og:description" content="&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;awk 是一种处理文本文件的语言，是一个强大的文本分析工具。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;之所以叫AWK是因为其取了三位创始人 Alfred Aho，Peter Weinberger, 和 Brian Kernighan 的Family">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-09-01T08:38:19.675Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Linux 命令- awk">
<meta name="twitter:description" content="&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;awk 是一种处理文本文件的语言，是一个强大的文本分析工具。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;之所以叫AWK是因为其取了三位创始人 Alfred Aho，Peter Weinberger, 和 Brian Kernighan 的Family">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://hcldirgit.github.io/2017/09/03/2. Linux 命令/71. Linux 命令- awk/"/>





  <title>Linux 命令- awk | 失落的乐章</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', '85*****1', 'auto');
  ga('send', 'pageview');
</script>


  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?87980c**************99ec5e26fb5";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>











  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">失落的乐章</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">技术面前，永远都是学生。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-message">
          <a href="/message" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-external-link"></i> <br />
            
            留言
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://hcldirgit.github.io/2017/09/03/2. Linux 命令/71. Linux 命令- awk/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="失落的乐章">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/0.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="失落的乐章">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Linux 命令- awk</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-09-03T01:57:34+08:00">
                2017-09-03
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;awk 是一种处理文本文件的语言，是一个强大的文本分析工具。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;之所以叫AWK是因为其取了三位创始人 Alfred Aho，Peter Weinberger, 和 Brian Kernighan 的Family Name的首字符。</p>
<h2 id="1-命令格式"><a href="#1-命令格式" class="headerlink" title="1. 命令格式"></a>1. 命令格式</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">awk [选项参数] <span class="string">'script'</span> var=value file(s)</div><div class="line">awk [选项参数] -f script var=value file(s)</div></pre></td></tr></table></figure>
<h2 id="2-命令参数"><a href="#2-命令参数" class="headerlink" title="2. 命令参数"></a>2. 命令参数</h2><ul>
<li>-F fs or –field-separator fs<br>指定输入文件折分隔符，fs是一个字符串或者是一个正则表达式，如-F:。</li>
<li>-v var=value or –asign var=value<br>赋值一个用户定义变量。</li>
<li>-f scripfile or –file scriptfile<br>从脚本文件中读取awk命令。</li>
<li>-mf nnn and -mr nnn<br>对nnn值设置内在限制，-mf选项限制分配给nnn的最大块数目；-mr选项限制记录的最大数目。这两个功能是Bell实验室版awk的扩展功能，在标准awk中不适用。</li>
<li>-W compact or –compat, -W traditional or –traditional<br>在兼容模式下运行awk。所以gawk的行为和标准的awk完全一样，所有的awk扩展都被忽略。</li>
<li>-W copyleft or –copyleft, -W copyright or –copyright<br>打印简短的版权信息。</li>
<li>-W help or –help, -W usage or –usage<br>打印全部awk选项和每个选项的简短说明。</li>
<li>-W lint or –lint<br>打印不能向传统unix平台移植的结构的警告。</li>
<li>-W lint-old or –lint-old<br>打印关于不能向传统unix平台移植的结构的警告。</li>
<li>-W posix<br>打开兼容模式。但有以下限制，不识别：/x、函数关键字、func、换码序列以及当fs是一个空格时，将新行作为一个域分隔符；操作符**和**=不能代替\^和^=；fflush无效。</li>
<li>-W re-interval or –re-inerval<br>允许间隔正则表达式的使用，参考(grep中的Posix字符类)，如括号表达式[[:alpha:]]。</li>
<li>-W source program-text or –source program-text<br>使用program-text作为源代码，可与-f命令混用。</li>
<li>-W version or –version<br>打印bug报告信息的版本。</li>
</ul>
<h2 id="3-基本用法"><a href="#3-基本用法" class="headerlink" title="3. 基本用法"></a>3. 基本用法</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;log.txt 文本内容如下</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">2 this is a <span class="built_in">test</span></div><div class="line">3 Are you like awk</div><div class="line">This<span class="string">'s a test</span></div><div class="line"><span class="string">10 There are orange,apple,mongo</span></div></pre></td></tr></table></figure>
<h3 id="用法一"><a href="#用法一" class="headerlink" title="用法一"></a>用法一</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">awk <span class="string">'&#123;[pattern] action&#125;'</span> &#123;filenames&#125;</div></pre></td></tr></table></figure>
<h4 id="实例：每行按空格或TAB分割，输出文本中的1、4行"><a href="#实例：每行按空格或TAB分割，输出文本中的1、4行" class="headerlink" title="实例：每行按空格或TAB分割，输出文本中的1、4行"></a>实例：每行按空格或TAB分割，输出文本中的1、4行</h4><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<strong>输出</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># awk '&#123;print $1,$4&#125;' log.txt                </span></div><div class="line">2 a</div><div class="line">3 like</div><div class="line">This<span class="string">'s </span></div><div class="line"><span class="string">10 orange,apple,mongo</span></div><div class="line"><span class="string">[root@localhost ~]# awk '</span>&#123;<span class="built_in">printf</span> <span class="string">"%-8s %-10s\n"</span>,<span class="variable">$1</span>,<span class="variable">$4</span>&#125;<span class="string">' log.txt  #格式化输出</span></div><div class="line"><span class="string">2        a         </span></div><div class="line"><span class="string">3        like      </span></div><div class="line"><span class="string">This'</span>s             </div><div class="line">10       orange,apple,mongo</div></pre></td></tr></table></figure>
<h3 id="用法二"><a href="#用法二" class="headerlink" title="用法二"></a>用法二</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">awk -F</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;-F 相当于内置变量 FS ，指定分隔字符</p>
<h4 id="实例：使用分隔符截取文档某段"><a href="#实例：使用分隔符截取文档某段" class="headerlink" title="实例：使用分隔符截取文档某段"></a>实例：使用分隔符截取文档某段</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># awk -F, '&#123;print $1,$2&#125;' log.txt   #使用“,”分割</span></div><div class="line">2 this is a <span class="built_in">test</span> </div><div class="line">3 Are you like awk </div><div class="line">This<span class="string">'s a test </span></div><div class="line"><span class="string">10 There are orange apple</span></div><div class="line"><span class="string">[root@localhost ~]# awk '</span>BEGIN&#123;FS=<span class="string">","</span>&#125; &#123;<span class="built_in">print</span> <span class="variable">$1</span>,<span class="variable">$2</span>&#125;<span class="string">' log.txt     #使用内建变量</span></div><div class="line"><span class="string">2 this is a test </span></div><div class="line"><span class="string">3 Are you like awk </span></div><div class="line"><span class="string">This'</span>s a <span class="built_in">test</span> </div><div class="line">10 There are orange apple</div><div class="line">[root@localhost ~]<span class="comment"># awk -F '[ ,]' '&#123;print $1,$2,$5&#125;' log.txt      #使用多个分隔符，先使用空格分割，然后对分割结果再使用“,”分割</span></div><div class="line">2 this <span class="built_in">test</span></div><div class="line">3 Are awk</div><div class="line">This<span class="string">'s a </span></div><div class="line"><span class="string">10 There apple</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<strong>说明</strong></p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;-F 选项的作用是指定分隔符，如果不加 -F 指定，则以空格或者 tab 为分隔符。print 为打印的动作，用来打印出某个字段。$1 为第一个字段，$2 为第二个字段，以此类推，有一个特殊的就是 $0 ，它表示整行。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;也可以使用自定义字符连接每个段，awk 的格式，-F 后紧跟单引号，然后里面为分隔符，print 的动作要用 {} 括起来，否则会报错。print 还可以打印自定义的内容，但是自定义的内容要用双引号括起来。</p>
<h3 id="用法三"><a href="#用法三" class="headerlink" title="用法三"></a>用法三</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">awk -v</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;-v 设置变量</p>
<h4 id="实例："><a href="#实例：" class="headerlink" title="实例："></a>实例：</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># awk -v a=1 '&#123;print $1,$1+a&#125;' log.txt</span></div><div class="line">2 3</div><div class="line">3 4</div><div class="line">This<span class="string">'s 1</span></div><div class="line"><span class="string">10 11</span></div><div class="line"><span class="string">[root@localhost ~]# awk -v a=1 -v b=a '</span>&#123;<span class="built_in">print</span> <span class="variable">$1</span>,<span class="variable">$1</span>+a,<span class="variable">$1b</span>&#125;<span class="string">' log.txt</span></div><div class="line"><span class="string">2 3 2a</span></div><div class="line"><span class="string">3 4 3a</span></div><div class="line"><span class="string">This'</span>s 1 This<span class="string">'sa</span></div><div class="line"><span class="string">10 11 10a</span></div></pre></td></tr></table></figure>
<h3 id="用法四"><a href="#用法四" class="headerlink" title="用法四"></a>用法四</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">awk -f &#123;awk脚本&#125; [文件名]</div></pre></td></tr></table></figure>
<h4 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">awk -f cal.awk log.txt</div></pre></td></tr></table></figure>
<h2 id="运算符"><a href="#运算符" class="headerlink" title="运算符"></a>运算符</h2><table>
<thead>
<tr>
<th>运算符</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>= += -= <em>= /= %= ^= *</em>=</td>
<td>赋值</td>
</tr>
<tr>
<td>?:</td>
<td>C条件表达式</td>
</tr>
<tr>
<td>\</td>
<td>\</td>
<td></td>
<td>逻辑或</td>
</tr>
<tr>
<td>&amp;&amp;</td>
<td>逻辑与</td>
</tr>
<tr>
<td>~ ~!</td>
<td>匹配正则表达式和不匹配正则表达式</td>
</tr>
<tr>
<td>&lt; &lt;= &gt; &gt;= != ==</td>
<td>关系运算符</td>
</tr>
<tr>
<td>空格</td>
<td>连接</td>
</tr>
<tr>
<td>+ -</td>
<td>加，减</td>
</tr>
<tr>
<td>* / %</td>
<td>乘，除与求余</td>
</tr>
<tr>
<td>+ - !</td>
<td>一元加，减和逻辑非</td>
</tr>
<tr>
<td>^ <em>*</em></td>
<td>求幂</td>
</tr>
<tr>
<td>++ –</td>
<td>增加或减少，作为前缀或后缀</td>
</tr>
<tr>
<td>$</td>
<td>字段引用</td>
</tr>
<tr>
<td>in</td>
<td>数组成员</td>
</tr>
</tbody>
</table>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;过滤第一列大于2的行</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># awk '$1&gt;2' log.txt</span></div><div class="line">3 Are you like awk</div><div class="line">This<span class="string">'s a test</span></div><div class="line"><span class="string">10 There are orange,apple,mongo</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;过滤第一列等于2的行</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># awk '$1==2 &#123;print $1,$3&#125;' log.txt</span></div><div class="line">2 is</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;过滤第一列大于2并且第二列等于 ‘Are’的行</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># awk '$1&gt;2 &amp;&amp; $2=="Are" &#123;print $1,$2,$3&#125;' log.txt</span></div><div class="line">3 Are you</div></pre></td></tr></table></figure>
<h2 id="内建变量"><a href="#内建变量" class="headerlink" title="内建变量"></a>内建变量</h2><table>
<thead>
<tr>
<th>变量</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>\$n</td>
<td>当前记录的第n个字段，字段间由FS分割</td>
</tr>
<tr>
<td>\$0</td>
<td>完整的输入记录</td>
</tr>
<tr>
<td>ARGC</td>
<td>命令行参数的数目</td>
</tr>
<tr>
<td>ARGIND</td>
<td>命令行中当前文件的位置（从0开始算）</td>
</tr>
<tr>
<td>ARGV</td>
<td>包含命令行参数的数组</td>
</tr>
<tr>
<td>CONVFMT</td>
<td>数字转换格式（默认值为%.6g）ENVIRON环境变量关联数组</td>
</tr>
<tr>
<td>ERRNO</td>
<td>最后一个系统错误的描述</td>
</tr>
<tr>
<td>FIELDWIDTHS</td>
<td>字段宽度列表（用空格键分割）</td>
</tr>
<tr>
<td>FILENAME</td>
<td>当前文件名</td>
</tr>
<tr>
<td>FNR</td>
<td>个文件分别计数的行号</td>
</tr>
<tr>
<td>FS</td>
<td>字段分割符（默认是任何空格）</td>
</tr>
<tr>
<td>IGNORECASE</td>
<td>如果为真，则进行忽略大小写的匹配</td>
</tr>
<tr>
<td>NF</td>
<td>输入字段的分隔符</td>
</tr>
<tr>
<td>NR</td>
<td>已经读出的记录数，就是行号，从1开始</td>
</tr>
<tr>
<td>OFMT</td>
<td>数字的输出格式（默认值是%.6g）</td>
</tr>
<tr>
<td>OFS</td>
<td>输出记录分隔符（输出换行符），输出时用指定的符号代替换行符</td>
</tr>
<tr>
<td>ORS</td>
<td>输出记录分隔符（默认值是一个换行符）</td>
</tr>
<tr>
<td>RLENGTH</td>
<td>由 match 函数所匹配的字符串的长度</td>
</tr>
<tr>
<td>RS</td>
<td>记录分隔符（默认是一个换行符）</td>
</tr>
<tr>
<td>RSTART</td>
<td>由 match 函数所匹配的字符串的第一个位置</td>
</tr>
<tr>
<td>SUBSEP</td>
<td>数组下标分隔符（默认值是/034）</td>
</tr>
</tbody>
</table>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line">$ awk <span class="string">'BEGIN&#123;printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n","FILENAME","ARGC","FNR","FS","NF","NR","OFS","ORS","RS";printf "---------------------------------------------\n"&#125; &#123;printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n",FILENAME,ARGC,FNR,FS,NF,NR,OFS,ORS,RS&#125;'</span>  log.txt</div><div class="line">FILENAME ARGC  FNR   FS   NF   NR  OFS  ORS   RS</div><div class="line">---------------------------------------------</div><div class="line">log.txt    2    1         5    1</div><div class="line">log.txt    2    2         5    2</div><div class="line">log.txt    2    3         3    3</div><div class="line">log.txt    2    4         4    4</div><div class="line">$ awk -F\<span class="string">' '</span>BEGIN&#123;<span class="built_in">printf</span> <span class="string">"%4s %4s %4s %4s %4s %4s %4s %4s %4s\n"</span>,<span class="string">"FILENAME"</span>,<span class="string">"ARGC"</span>,<span class="string">"FNR"</span>,<span class="string">"FS"</span>,<span class="string">"NF"</span>,<span class="string">"NR"</span>,<span class="string">"OFS"</span>,<span class="string">"ORS"</span>,<span class="string">"RS"</span>;<span class="built_in">printf</span> <span class="string">"---------------------------------------------\n"</span>&#125; &#123;<span class="built_in">printf</span> <span class="string">"%4s %4s %4s %4s %4s %4s %4s %4s %4s\n"</span>,FILENAME,ARGC,FNR,FS,NF,NR,OFS,ORS,RS&#125;<span class="string">'  log.txt</span></div><div class="line"><span class="string">FILENAME ARGC  FNR   FS   NF   NR  OFS  ORS   RS</span></div><div class="line"><span class="string">---------------------------------------------</span></div><div class="line"><span class="string">log.txt    2    1    '</span>    1    1</div><div class="line">log.txt    2    2    <span class="string">'    1    2</span></div><div class="line"><span class="string">log.txt    2    3    '</span>    2    3</div><div class="line">log.txt    2    4    <span class="string">'    1    4</span></div><div class="line"><span class="string"># 输出顺序号 NR, 匹配文本行号</span></div><div class="line"><span class="string">$ awk '</span>&#123;<span class="built_in">print</span> NR,FNR,<span class="variable">$1</span>,<span class="variable">$2</span>,<span class="variable">$3</span>&#125;<span class="string">' log.txt</span></div><div class="line"><span class="string">---------------------------------------------</span></div><div class="line"><span class="string">1 1 2 this is</span></div><div class="line"><span class="string">2 2 3 Are you</span></div><div class="line"><span class="string">3 3 This'</span>s a <span class="built_in">test</span></div><div class="line">4 4 10 There are</div><div class="line"><span class="comment"># 指定输出分割符</span></div><div class="line">$  awk <span class="string">'&#123;print $1,$2,$5&#125;'</span> OFS=<span class="string">" $ "</span>  log.txt</div><div class="line">---------------------------------------------</div><div class="line">2 $ this $ <span class="built_in">test</span></div><div class="line">3 $ Are $ awk</div><div class="line">This<span class="string">'s $ a $</span></div><div class="line"><span class="string">10 $ There $</span></div></pre></td></tr></table></figure>
<h2 id="使用正则，字符串匹配"><a href="#使用正则，字符串匹配" class="headerlink" title="使用正则，字符串匹配"></a>使用正则，字符串匹配</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;输出第二列包含 “th”，并打印第二列与第四列</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># awk '$2 ~ /th/ &#123;print $2,$4&#125;' log.txt</span></div><div class="line">this a</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<strong> ~ 表示模式开始。//中是模式。</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># awk '/re/' log.txt</span></div><div class="line">3 Are you like awk</div><div class="line">10 There are orange,apple,mongo</div></pre></td></tr></table></figure>
<h2 id="忽略大小写"><a href="#忽略大小写" class="headerlink" title="忽略大小写"></a>忽略大小写</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># awk 'BEGIN&#123;IGNORECASE=1&#125; /this/' log.txt</span></div><div class="line">2 this is a <span class="built_in">test</span></div><div class="line">This<span class="string">'s a test</span></div></pre></td></tr></table></figure>
<h2 id="模式取反"><a href="#模式取反" class="headerlink" title="模式取反"></a>模式取反</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># awk '$2 !~ /th/ &#123;print $2,$4&#125;' log.txt</span></div><div class="line">Are like</div><div class="line">a </div><div class="line">There orange,apple,mongo</div><div class="line">[root@localhost ~]<span class="comment"># awk '! /th/ &#123;print $2,$4&#125;' log.txt</span></div><div class="line">Are like</div><div class="line">a </div><div class="line">There orange,apple,mongo</div></pre></td></tr></table></figure>
<h2 id="awk-脚本"><a href="#awk-脚本" class="headerlink" title="awk 脚本"></a>awk 脚本</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;关于 awk 脚本，需要注意两个关键词 BEGIN 和 END。</p>
<ul>
<li>BEGIN {这里面放的是执行前的语句｝</li>
<li>END ｛这里面放的是处理完所有的行后要执行的语句｝</li>
<li>｛这里面放的是处理每一行时要执行的语句｝</li>
</ul>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;假设有这么一个文件（学生成绩表）</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># cat score.txt </span></div><div class="line">Marry   2143 78 84 77</div><div class="line">Jack    2321 66 78 45</div><div class="line">Tom     2122 48 77 71</div><div class="line">Mike    2537 87 97 95</div><div class="line">Bob     2415 40 57 62</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;awk 脚本如下</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># cat cal.awk</span></div><div class="line"><span class="comment">#!/bin/awk -f</span></div><div class="line"><span class="comment">#运行前</span></div><div class="line">BEGIN &#123;</div><div class="line">    math = 0</div><div class="line">    english = 0</div><div class="line">    computer = 0</div><div class="line"> </div><div class="line">    <span class="built_in">printf</span> <span class="string">"NAME    NO.   MATH  ENGLISH  COMPUTER   TOTAL\n"</span></div><div class="line">    <span class="built_in">printf</span> <span class="string">"---------------------------------------------\n"</span></div><div class="line">&#125;</div><div class="line"><span class="comment">#运行中</span></div><div class="line">&#123;</div><div class="line">    math+=<span class="variable">$3</span></div><div class="line">    english+=<span class="variable">$4</span></div><div class="line">    computer+=<span class="variable">$5</span></div><div class="line">    <span class="built_in">printf</span> <span class="string">"%-6s %-6s %4d %8d %8d %8d\n"</span>, <span class="variable">$1</span>, <span class="variable">$2</span>, <span class="variable">$3</span>,<span class="variable">$4</span>,<span class="variable">$5</span>, <span class="variable">$3</span>+<span class="variable">$4</span>+<span class="variable">$5</span></div><div class="line">&#125;</div><div class="line"><span class="comment">#运行后</span></div><div class="line">END &#123;</div><div class="line">    <span class="built_in">printf</span> <span class="string">"---------------------------------------------\n"</span></div><div class="line">    <span class="built_in">printf</span> <span class="string">"  TOTAL:%10d %8d %8d \n"</span>, math, english, computer</div><div class="line">    <span class="built_in">printf</span> <span class="string">"AVERAGE:%10.2f %8.2f %8.2f\n"</span>, math/NR, english/NR, computer/NR</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;执行结果</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># awk -f cal.awk score.txt</span></div><div class="line">NAME    NO.   MATH  ENGLISH  COMPUTER   TOTAL</div><div class="line">---------------------------------------------</div><div class="line">Marry  2143     78       84       77      239</div><div class="line">Jack   2321     66       78       45      189</div><div class="line">Tom    2122     48       77       71      196</div><div class="line">Mike   2537     87       97       95      279</div><div class="line">Bob    2415     40       57       62      159</div><div class="line">---------------------------------------------</div><div class="line">  TOTAL:       319      393      350 </div><div class="line">AVERAGE:     63.80    78.60    70.00</div></pre></td></tr></table></figure>
<h2 id="另外一些实例"><a href="#另外一些实例" class="headerlink" title="另外一些实例"></a>另外一些实例</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;awk 的 hello world 程序为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">BEGIN &#123;<span class="built_in">print</span> <span class="string">"Hello, world!"</span>&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;计算文件大小</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">[root@localhost ~]<span class="comment"># ls -l *.txt | awk '&#123;sum+=$6&#125; END &#123;print sum&#125;'</span></div><div class="line">30</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;从文件中找出长度大于80的行</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">awk <span class="string">'lenght&gt;80'</span> log.txt</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;打印九九乘法表</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">seq 9 | sed <span class="string">'H;g'</span> | awk -v RS=<span class="string">''</span> <span class="string">'&#123;for(i=1;i&lt;=NF;i++)printf("%dx%d=%d%s", i, NR, i*NR, i==NR?"\n":"\t")&#125;'</span></div></pre></td></tr></table></figure>
      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/正则表达式/" rel="tag"># 正则表达式</a>
          
            <a href="/tags/Linux命令/" rel="tag"># Linux命令</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/09/03/2. Linux 命令/55. Linux 命令- route/" rel="next" title="Linux 命令- route">
                <i class="fa fa-chevron-left"></i> Linux 命令- route
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/03/2. Linux 命令/48. Linux 命令- vmstat/" rel="prev" title="Linux 命令- vmstat">
                Linux 命令- vmstat <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/0.png"
               alt="失落的乐章" />
          <p class="site-author-name" itemprop="name">失落的乐章</p>
           
              <p class="site-description motion-element" itemprop="description">失落的乐章的Blog</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/">
                <span class="site-state-item-count">627</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">38</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hcldirgit" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-命令格式"><span class="nav-number">1.</span> <span class="nav-text">1. 命令格式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-命令参数"><span class="nav-number">2.</span> <span class="nav-text">2. 命令参数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-基本用法"><span class="nav-number">3.</span> <span class="nav-text">3. 基本用法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#用法一"><span class="nav-number">3.1.</span> <span class="nav-text">用法一</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#实例：每行按空格或TAB分割，输出文本中的1、4行"><span class="nav-number">3.1.1.</span> <span class="nav-text">实例：每行按空格或TAB分割，输出文本中的1、4行</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#用法二"><span class="nav-number">3.2.</span> <span class="nav-text">用法二</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#实例：使用分隔符截取文档某段"><span class="nav-number">3.2.1.</span> <span class="nav-text">实例：使用分隔符截取文档某段</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#用法三"><span class="nav-number">3.3.</span> <span class="nav-text">用法三</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#实例："><span class="nav-number">3.3.1.</span> <span class="nav-text">实例：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#用法四"><span class="nav-number">3.4.</span> <span class="nav-text">用法四</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#实例"><span class="nav-number">3.4.1.</span> <span class="nav-text">实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#运算符"><span class="nav-number">4.</span> <span class="nav-text">运算符</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#内建变量"><span class="nav-number">5.</span> <span class="nav-text">内建变量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用正则，字符串匹配"><span class="nav-number">6.</span> <span class="nav-text">使用正则，字符串匹配</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#忽略大小写"><span class="nav-number">7.</span> <span class="nav-text">忽略大小写</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模式取反"><span class="nav-number">8.</span> <span class="nav-text">模式取反</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#awk-脚本"><span class="nav-number">9.</span> <span class="nav-text">awk 脚本</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#另外一些实例"><span class="nav-number">10.</span> <span class="nav-text">另外一些实例</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">失落的乐章</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  





  

  

  

  

  

  

</body>
</html>
